package day14;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Server2 {
    //保存进入了聊天室的客户端对象
    static List<Socket> list=new ArrayList<>();
    public static void main(String[] args) throws IOException {
        ServerSocket server=new ServerSocket(9999);
        while (true){
            Socket client=server.accept();
            list.add(client);//类似于加群
            System.out.println("聊天室:"+list.size()+"人");
            //创建线程:负责多次客户端读取 且给其他所有客户端再写入
            new ServerThread2(client).start();
        }
    }
}
class ServerThread2 extends Thread{
    Socket client;
    public ServerThread2(Socket client) {
        this.client = client;
    }
    public void run() {
        try{
            BufferedReader br=new BufferedReader(
                    new InputStreamReader(client.getInputStream()));
            while (true){
                String msg=br.readLine();//读取当前客户端数据
                if(msg!=null){
                    System.out.println(msg);
                    //如果客户端写入的数据包含了esc 就表示想退出
                    if(msg.contains("esc")){
                        Server2.list.remove(client);
                        int i=msg.indexOf("说");
                        String name=msg.substring(0,i);
                        System.out.println(name+"已退出,当前聊天室的人数:"+Server2.list.size());
                        break;
                    }
                    //向其他客户端写入
                    for(Socket s:Server2.list){
                        if(s!=client){
                            try{
                                s.getOutputStream().write((msg+"\n").getBytes());
                            }catch (Exception e){
                            }
                        }
                    }
                }
            }
        }catch (Exception e){

        }
    }
}